/*
 * @Author: Mr.Cong Wei
 * @Date: 2022-07-26 20:46:07
 * @LastEditTime: 2022-07-26 22:18:13
 */
const fs = require('fs')
const cliProgress = require('cli-progress')

const axios = require('./request')
const { convertContent } = require('./convertHtml')
const { resolve } = require('path')
const { outDir } = require('./setting')


async function saveFs(title, list) {
    let amount = 0
    const bar = new cliProgress.SingleBar({
        format: '下载进度：[{bar}] {percentage}% | 预估时间: {eta}s | {value}/{total}',
        barIncompleteChar: '-'
    }, cliProgress.Presets.rect)
    bar.start(list.length, amount) // 初始化总数，当前数

    const ws = fs.createWriteStream(resolve(outDir, `${title}.txt`), {
        flags: 'a' // 表示写入方式为追加
    })
    for (const b of list) {
        const res = await axios.get(b.url)
        bar.increment() // +1
        bar.update(amount += 1)
        const content = convertContent(res.data)
        ws.write(b.title + '\n')  // \n换行符
        ws.write(content + '\n')
    }
    ws.end()
    process.exit()

}

module.exports = saveFs